package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"math"
	"my-zero-tiktok/apps/user/pb/pb"
	"my-zero-tiktok/apps/user/rpc/internal/svc"
	"my-zero-tiktok/common/constant"
	"my-zero-tiktok/common/paginate"
	"strconv"
)

type FollowUserListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFollowUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FollowUserListLogic {
	return &FollowUserListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// FollowUserList 我的关注列表
func (l *FollowUserListLogic) FollowUserList(in *pb.UserListRequest) (*pb.UserListResponse, error) {
	var userIDs []int64
	offset := paginate.GetOffset(in.Page, in.PerPage)
	followKey := fmt.Sprintf("%s:%d", constant.FollowKey, in.Id)
	pairs, err := l.svcCtx.Redis.ZrevrangebyscoreWithScoresAndLimitCtx(
		l.ctx, followKey, 0, math.MaxInt, int(offset), int(in.PerPage),
	)
	if err == nil {
		if len(pairs) > 0 {
			for _, pair := range pairs {
				id, _ := strconv.ParseInt(pair.Key, 10, 64)
				userIDs = append(userIDs, id)
			}
		}
	} else {
		userIDs, err = l.svcCtx.RelationModel.FollowListByPage(l.ctx, in.Id, offset, in.PerPage)
		if err != nil {
			return nil, err
		}
	}

	if len(userIDs) == 0 {
		return &pb.UserListResponse{}, nil
	}
	var resp pb.UserListResponse
	users, err := l.svcCtx.UserModel.UserList(l.ctx, userIDs)
	userList := make([]*pb.User, len(users))
	for i, user := range users {
		userList[i] = &pb.User{Id: user.Id, Name: user.Name}
	}
	resp.List = userList
	return &resp, nil
}
